<?PHP
/** 
 * To install Opol:
 *	set:
 *	 $username to the root username for MySQL.
 *	 $password to the root password for MySQL.
 *	 $install_dir to the directory to install the files to.
 *	These variables also must be set in the backup.sh or backup.bat files.
 * 
 *	After that run 'php -f INSTALL.PHP' either:
 *	  - as root (GNU/Linux, Mac, Unix) (sudo php -f INSTALL.PHP)
 *	  - in an administrator command prompt (Windows)
 */
 
function input($prompt) {
  print $prompt;
  $stdin = fopen("php://stdin", "r");
  $input = fgets($stdin, 255);
  fclose($stdin);
  return $input;
}

$username = input("Enter MySQL username:");
$password = input("Enter MySQL password:");
$install_dir = input("Enter Opol installation directory:");

if (!$username || !$password || !$install_dir) {
	print "All values are required\n";
	die();
}

/* Create the Opol database. */

$mysqli = new mysqli('localhost', $username, $password);
$mysqli->query ("CREATE DATABASE opol");

/* Create the tables and the users. */

$init_sql = file_get_contents ("init.sql");
$statements = explode (";", $init_sql);
foreach ($statements as $query) {
	$query = ltrim($query);
	if (strlen ($query) == 0)
		continue;
	$query .= ";";
	$mysqli->query ($query);
}

$mysqli->close();

/* Copy the files over. */

$files = array (
	"about.php",
	"automatic_updater.php",
	"config.ini",
	"customer.php",
	"database.php",
	"drop_down_menu_bar.css",
	"employees.php",
	"index.php",
	"insert.php",
	"login_info.php",
	"machines.php",
	"materials.php",
	"menu.php",
	"new_entry.php",
	"new_order.php",
	"new_phase.php",
	"opol.css",
	"opol.png",
	"order.php",
	"phase.php",
	"schedule.php",
	"table.php",
	"update_customer.php",
	"update_employee.php",
	"update_entry.php",
	"update_machine.php",
	"update_material.php",
	"update_order.php",
	"update_phase.php",
	"view_day.php",
	"view_employee.php",
	"view_label.php",
	"view_machine.php",
	"view_month.php",
	"view_order.php",
	"view_week.php",
	"views.php"
);

foreach ($files as $file_name) {
	copy ($file_name, "$install_dir/$file_name");
}

// This will determine the OS that PHP is currently running on.
$os = strtolower (substr (php_uname('s'), 0, 3));

switch($os) {
	case "win":
		//windows stuff
    print "Be sure to configure the backup.bat file!";
		eval('AT 1AM /EVERY:M,T,W,Th,F,S,Su "backup.bat"');
		break;
	default:
    //unix stuff
		//If your crontab is already being used, then this will have to be manually added.
    print "Be sure to configure the backup.sh file!";
		eval("crontab ./backup.sh");
		break;
}

?>